﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Core.DataAccess.IRepositories;
using System.ComponentModel.Composition;

namespace Core.DataAccess.Repositories
{
    [Export(typeof(IStatusUpdateRepository))]
    public class StatusUpdateRepository : IStatusUpdateRepository
    {
        private Connection conn;
        public StatusUpdateRepository()
        {
            conn = new Connection();
        }

        public long SaveStatusUpdate(StatusUpdate statusUpdate)
        {
            using (MXHEntities context = conn.GetContext())
            {
                if (statusUpdate.StatusUpdateID > 0)
                {
                    context.StatusUpdates.Attach(new StatusUpdate { StatusUpdateID = statusUpdate.StatusUpdateID });
                    context.StatusUpdates.ApplyCurrentValues(statusUpdate);
                }
                else
                {
                    statusUpdate.CreateDate = DateTime.Now;
                    context.StatusUpdates.AddObject(statusUpdate);
                }
                context.SaveChanges();
                return statusUpdate.StatusUpdateID;
            }
        }


        public List<StatusUpdate> GetStatusUpdateByAccountID(int accountID)
        {
            List<StatusUpdate> result = new List<StatusUpdate>();
            using (MXHEntities context = conn.GetContext())
            {
                IEnumerable<StatusUpdate> statusUpdates = from n in context.StatusUpdates
                                                          where n.AccountID == accountID
                                                          orderby n.CreateDate descending
                                                          select n;
                result = statusUpdates.ToList();
            }
            return result;
        }

        public List<StatusUpdate> GetNewestStatusUpdateOfFriends(List<int> friendIDList)
        {
            List<StatusUpdate> result = new List<StatusUpdate>();
            using (MXHEntities context = conn.GetContext())
            {
                //friendIDList.ForEach(n => result.Add(context.StatusUpdates.Where(o => o.AccountID == n).OrderByDescending(o=>o.CreateDate).FirstOrDefault()));                
                foreach (int id in friendIDList)
                {
                    var item = from st in context.StatusUpdates
                               where st.AccountID == id
                               select st;
                    if (item.Count() > 0)
                        result.AddRange(item.ToList());
                }
            }
            //result.RemoveAll(n => n == null);
            result = result.OrderByDescending(n => n.CreateDate).ThenByDescending(n => n.CreateDate.TimeOfDay).ToList();
            return result;
        }
    }
}
